package romaremez.teachingSystem.controller;

import org.springframework.beans.factory.annotation.Autowired;
import romaremez.teachingSystem.Authorizer;
import romaremez.teachingSystem.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class MainController {

    @Autowired
    Authorizer authorizer;

    @RequestMapping("/")
    public String main(Model ui)
    {
       return "index";
    }


    @RequestMapping(value="login", method= RequestMethod.GET)
    public String loginUser(Model ui)
    {
        ui.addAttribute("user", new User());
        ui.addAttribute("destination", "authorization/login");
        return "authorization/loginForm";
    }

    @RequestMapping(value="authorization/login", method= RequestMethod.POST)
    public String authorizeUser(User user, Model ui)
    {
        User someUser = authorizer.authorizeUser(user);
        String destination;
        if (someUser != null) {
            destination = "profile";
        } else {
            destination = "authorization/loginForm";
        }
        ui.addAttribute("message", destination);
        return destination;
    }

    @RequestMapping(value="register", method= RequestMethod.GET)
    public String registerUser(Model ui)
    {
        ui.addAttribute("user", new User());
        ui.addAttribute("destination", "authorization/register");
        return "authorization/loginForm";
    }

    @RequestMapping(value="authorization/register", method= RequestMethod.POST)
    public String saveUser(User user, Model ui)
    {
        authorizer.acceptNewUser(user);
        ui.addAttribute("message", "Now you can login");
        return "index";
    }
}